package com.geping.etl.common.controller;

import com.alibaba.fastjson.JSON;
import com.geping.etl.common.entity.*;
import com.geping.etl.common.service.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class Sys_Auth_RoleController {

    @Autowired
    private Sys_Auth_RoleService sysauthroleservice;
    @Autowired
    private Sys_MenuService sysmenuservice;
    @Autowired
    private Report_InfoService reprotinfoservice;
    @Autowired
    private Sys_Report_OperateService sysreportoperateservice;
    @Autowired
    private Sys_Auth_Role_ResourceService sysauthroleresourceservice;
    @Autowired
    private Sys_Auth_Role_UserService sysAuthRoleUserService;
    @Autowired
    private Sys_UserService sysUserService;
    @Autowired
    private Sys_SubjectService sss;
    @Autowired
    private Sys_MenuService sys_menuService;
    @Autowired
    private Sys_UserAndOrgDepartmentService sys_UserAndOrgDepartmentService;


    private List<Sys_Auth_Role_User> roleUserList;

    /**
     * 角色管理首页
     *
     * @return
     */
    @RequestMapping(value = "/getRole_Ui", method = RequestMethod.GET)
    public ModelAndView getRole_Ui() {
        ModelAndView model = new ModelAndView();
        model.setViewName("common/sys_role");
        return model;
    }

    @RequestMapping(value = "/audit_authority", method = RequestMethod.GET)
    public ModelAndView Audit_authority(HttpServletRequest request) {
        ModelAndView model = new ModelAndView();

        //获取所有人员信息
        List<Sys_UserAndOrgDepartment> users = sys_UserAndOrgDepartmentService.findAllSysUser().stream().distinct().collect(Collectors.toList());
        Map<String, String> map = users.stream().collect(Collectors.toMap(Sys_UserAndOrgDepartment::getUsercname, Sys_UserAndOrgDepartment::getLoginid, (k1, k2) -> k2));
        model.addObject("users", users);
        model.addObject("map", JSON.toJSONString(map));
        model.setViewName("common/sys_audit_authority");
        return model;
    }


    @RequestMapping(value = "/getAllSys_Auth_Role", method = RequestMethod.POST)
    public void getAllSys_Auth_Role(String sign, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setContentType("text/html");
            response.setContentType("text/plain; charset=utf-8");
            List<Sys_Subject> subjectList = sss.findAllSubject();
            if (StringUtils.isNotBlank(sign)) {
                final List<Integer> ids = Arrays.asList(4, 5, 8, 9, 25);
                subjectList = subjectList.stream().filter(sys_subject -> ids.contains(sys_subject.getId())).collect(Collectors.toList());
                ;
            }
            List<Sys_Menu> menus = sss.findAllMenu("#", "8");
            JSONObject json = new JSONObject();
            out = response.getWriter();
            json.put("rows", subjectList);
            json.put("menus", menus);
            json.put("total", subjectList.size());   // 将总页数传到页面上显示
            out.write(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }


    @RequestMapping(value = "/findRoleBySubjectId", method = RequestMethod.POST)
    public void findRoleBySubjectId(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");
        response.setContentType("text/plain; charset=utf-8");
        String subjectId = request.getParameter("subjectId");
        if (subjectId == null || subjectId.equals("")) {
            subjectId = "1";
        }
        List<Sys_Auth_Role> roleList = sysauthroleservice.findRoleBySubjectId(subjectId);
        PrintWriter out = null;
        try {
            JSONObject json = new JSONObject();
            out = response.getWriter();
            json.put("roleList", roleList);
            out.write(json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    //
    @RequestMapping(value = "/datagridRoleBySubId", method = RequestMethod.POST)
    public void datagridRoleBySubId(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");
        response.setContentType("text/plain; charset=utf-8");
        String subjectId = request.getParameter("subjectId");

        List<Sys_Auth_Role> roleList = sysauthroleservice.findRoleBySubjectId(subjectId);
        PrintWriter out = null;
        JSONObject json = new JSONObject();
        try {
            out = response.getWriter();
            json.put("rows", roleList);
            json.put("total", roleList.size()); // 将总页数传到页面上显示
            out.write(json.toString());
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "/findReportBySubjectId", method = RequestMethod.POST)
    public void findReportBySubjectId(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");
        response.setContentType("text/plain; charset=utf-8");
        String subjectId = request.getParameter("subjectId");
        if (subjectId == null || subjectId.equals("")) {
            subjectId = "1";
        }
        List<Sys_UserAndOrgDepartment> lists = sys_UserAndOrgDepartmentService.findAllSysUser();
        final Map<String, String> loginIdMapName = lists.stream().collect(Collectors.toMap(Sys_UserAndOrgDepartment::getLoginid, Sys_UserAndOrgDepartment::getUsercname, (k1, k2) -> k2));
        String east2Huachen = (String) request.getSession().getAttribute("east2Huachen");

        List<Report_Info> roleList = reprotinfoservice.getReportBySubjectId(subjectId, east2Huachen);

        if (roleList != null && roleList.size() > 0) {
            for (Report_Info report_info : roleList) {
                if (StringUtils.isNotBlank(report_info.getUpdateTime())) {
                    String groupInfo = report_info.getUpdateTime();
                    if ("8".equals(subjectId)) {
                        Map<String, Map<String, List<String>>> groups = JSON.parseObject(groupInfo, Map.class);
                        Set<String> set = groups.keySet();
                        for (String s : set) {
                            Map<String, List<String>> tempMap = groups.get(s);
                            Set<String> tempSet = tempMap.keySet();
                            for (String s1 : tempSet) {
                                List<String> users = tempMap.get(s1);
                                List<String> newList = users.stream().map(s2 -> loginIdMapName.get(s2)).collect(Collectors.toList());
                                tempMap.put(s1, newList);
                            }
                            groups.put(s, tempMap);
                        }
                        String newString = JSON.toJSONString(groups);
                        report_info.setUpdateTime(newString);
                    } else {
                        Map<String, List<String>> groups = JSON.parseObject(groupInfo, Map.class);
                        Set<String> set = groups.keySet();
                        for (String s : set) {
                            List<String> users = groups.get(s);
                            List<String> newList = users.stream().map(s2 -> loginIdMapName.get(s2)).collect(Collectors.toList());
                            groups.put(s, newList);
                        }
                        String newString = JSON.toJSONString(groups);
                        report_info.setUpdateTime(newString);
                    }

                }
            }
        }

        PrintWriter out = null;
        try {
            JSONObject json = new JSONObject();
            out = response.getWriter();
            json.put("roleList", roleList);
            out.write(json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }


    //新增角色
    @RequestMapping(value = "/addSys_Auth_Role", method = RequestMethod.POST)
    public void addSys_Auth_role(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            String subjectId = "2";
            String rolename = request.getParameter("roleNameadd");//角色名称
            String roledesc = request.getParameter("roleDescadd");//角色描述
            //Sys_Auth_Role role = sysauthroleservice.getRoleName(rolename);
            Sys_Auth_Role role = sysauthroleservice.getRoleNameBySubjectId(rolename, subjectId);
            request.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            if (role != null) {
                out.write("2");
            } else {
                Sys_Auth_Role auth = new Sys_Auth_Role();
                auth.setSubjectId(subjectId);
                auth.setRoleName(rolename);
                auth.setDescription(roledesc);

                Sys_Auth_Role authrole = sysauthroleservice.save(auth);
                if (authrole != null) {
                    out.write("1");
                } else {
                    out.write("0");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }


    //根据角色名模糊查询角色
    @RequestMapping(value = "/getSys_Auth_RoleByLikeRoleName", method = RequestMethod.POST)
    public void getSys_Auth_RoleByLikeRoleName(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");
        response.setContentType("text/plain; charset=utf-8");
        String subjectId = request.getParameter("subjectId");
        String roleName = request.getParameter("roleName").replaceAll("%", "%25");
        PrintWriter out = null;
        try {
            if (roleName.contains("_")) {
                roleName = roleName.replace("_", "djskdffhdfka");
            }
            request.setCharacterEncoding("UTF-8");
            List<Sys_Auth_Role> roleList = new ArrayList<>();
            if (StringUtils.isNotBlank(roleName)) {
                roleList = sysauthroleservice.getSys_Auth_RoleByLikeRoleName(subjectId, roleName);
            } else {
                roleList = sysauthroleservice.findRoleBySubjectId(subjectId);
            }
            JSONObject json = new JSONObject();
            out = response.getWriter();
            json.put("roleList", roleList);
            out.print(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }


    //修改角色名称和角色描述
    @RequestMapping(value = "/updateRoleNameAndRoleDesc", method = RequestMethod.POST)
    public void updateRoleNameAndRoleDesc(HttpServletRequest request, HttpServletResponse response) {
        String roleName = request.getParameter("roleNameEdit");
        String desc = request.getParameter("roleDescEdit");
        String id = request.getParameter("editId");
        String isEditRoleName = request.getParameter("isEditRoleName");
        String subjectId = "2";
        Sys_Auth_Role sar = new Sys_Auth_Role();
        sar.setDescription(desc);
        sar.setRoleName(roleName);
        sar.setId(Integer.valueOf(id));
        PrintWriter out = null;
        try {
            out = response.getWriter();
            //isEditRoleName等于1时，角色名改变，否则角色名不变
            if (isEditRoleName.equals("1")) {
                //Sys_Auth_Role auth = sysauthroleservice.getRoleName(roleName);
                Sys_Auth_Role auth = sysauthroleservice.getRoleNameBySubjectId(roleName, subjectId);
                //如果角色名称已经存在，保存失败
                if (auth != null) {
                    out.write("2");
                } else {
                    //为空时表示  角色名称不存在，可以使用
                    int result = sysauthroleservice.updateRoleNameAndRoleDesc(sar);
                    if (result > 0) {
                        out.write("1");
                    } else {
                        out.write("0");
                    }

                }
            } else {
                //角色名称未变的情况
                int result = sysauthroleservice.updateRoleNameAndRoleDesc(sar);
                if (result > 0) {
                    out.write("1");
                } else {
                    out.write("0");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }


    @RequestMapping(value = "/stopSys_Auth_Role", method = RequestMethod.POST)
    public void stopSys_Auth_Role(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");
        response.setContentType("text/plain; charset=utf-8");
        String roleId = request.getParameter("id");
        StringBuffer result = new StringBuffer();
        int listSize = 0;
        int sum = 0;
        String d = ",";
        roleUserList = sysAuthRoleUserService.findRoleUserByRoleId(roleId);
        if (roleUserList.size() > 0) {
            listSize = roleUserList.size();
            for (Sys_Auth_Role_User sysAuthRoleUser : roleUserList) {
                sum = sum + 1;
                if (sum == listSize) {
                    String r1 = sysUserService.findSys_UserById(Integer.valueOf(sysAuthRoleUser.getUserId()));
                    if (r1 == null || r1.equals("null")) {
                        result.append(sysauthroleservice.deleteSys_Auth_Role(Integer.valueOf(roleId)) + "");
                        break;
                    } else {
                        result.append(r1);
                    }
                } else {
                    String r1 = sysUserService.findSys_UserById(Integer.valueOf(sysAuthRoleUser.getUserId()));
                    if (r1 == null || r1.equals("null")) {
                        result.append(sysauthroleservice.deleteSys_Auth_Role(Integer.valueOf(roleId)) + "");
                        break;
                    } else {
                        result.append(r1 + d);
                    }
                }
            }
        } else {
            result.append(sysauthroleservice.deleteSys_Auth_Role(Integer.valueOf(roleId)) + "");
        }
        JSONObject json = new JSONObject();
        PrintWriter out;

        try {
            out = response.getWriter();
            json.put("result", result.toString());
            out.print(json.toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 角色资源管理模块
     *
     * @param request
     * @param response
     */

    //显示角色资源管理中的“菜单权限”，“报表权限”，“机构管理”，“报表操作权限”
    @RequestMapping(value = "/getSys_Menu", method = RequestMethod.POST)
    public void findAllSysRoleResource(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");
        response.setContentType("text/plain; charset=utf-8");
        //subjectId 是所分配功能对应页面的id
        String subjectId = request.getParameter("subjectId");
        //先判断是否已经有权限，如果有权限的话，先回显权限  roleId 角色id
        String roleId = request.getParameter("roleId");
        List<Sys_Auth_Role_Resource> list = sysauthroleresourceservice.findAllByRoleId(roleId);

        //菜单权限(根据subjectId获取)
        List<Sys_Menu> menulist = sysmenuservice.getMenuBySubjectId(subjectId);

        //报表权限
        String east2Huachen = (String) request.getSession().getAttribute("east2Huachen");

        Iterable<Report_Info> reportinfo = reprotinfoservice.getReportBySubjectId(subjectId, east2Huachen);
        Iterator<Report_Info> report = reportinfo.iterator();
        List<Report_Info> reportlist = new ArrayList<>();
        while (report.hasNext()) {
            Report_Info info = report.next();
            reportlist.add(info);
        }
        //机构角色权限
		/*Iterable<Sys_Org> sysorg = sysorgservice.findAllSysOrg();
		Iterator<Sys_Org> sys_org = sysorg.iterator();
		List<Sys_Org> orglist = new ArrayList<>();
		while(sys_org.hasNext()){
			Sys_Org org = sys_org.next();
			orglist.add(org);
		}*/

        //报表操作权限
        Iterable<Sys_Report_Operate> sysreportoperate = sysreportoperateservice.findAll();
        Iterator<Sys_Report_Operate> sys_report_operate = sysreportoperate.iterator();
        List<Sys_Report_Operate> operatelist = new ArrayList<>();
        while (sys_report_operate.hasNext()) {
            Sys_Report_Operate operate = sys_report_operate.next();
            if (subjectId.equals(operate.getSubjectId())) {
                operatelist.add(operate);
            }
        }

        JSONObject json = new JSONObject();
        PrintWriter out;

        try {
            out = response.getWriter();
            json.put("list", list);
            json.put("menulist", menulist);
            json.put("reportlist", reportlist);
            //json.put("orglist", orglist);
            json.put("operatelist", operatelist);
            out.print(json.toString());

            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //点击角色分配中的保存按钮
    @RequestMapping(value = "/saveSysAuthRoleResourceButton", method = RequestMethod.POST)
    public void saveSysAuthRoleResourceButton(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String jsonStr = request.getParameter("mydata");
        JSONArray array = JSONArray.fromObject(jsonStr);

        //只要点了保存按钮，不管数据库中是否有此roleId，都会执行一次删除方法。
        JSONObject jsontwo;
        for (int i = 0; i < 1; i++) {
            jsontwo = (JSONObject) array.get(i);
            String role_Id = jsontwo.get("roleId").toString();

            //Integer deleteforSysAuthRoleResource;
            //若要保存role_Id的数据到数据库时，先删除所有role_Id之前的数据
            //deleteforSysAuthRoleResource =
            sysauthroleresourceservice.deleteSysAuthRoleResource(role_Id);
        }

        JSONObject jsonOne;
        for (int i = 0; i < array.size(); i++) {
            jsonOne = (JSONObject) array.get(i);
            Sys_Auth_Role_Resource sys_auth_role_resource = new Sys_Auth_Role_Resource();

            String subjectId = jsonOne.get("subjectId").toString();
            String roleId = jsonOne.get("roleId").toString();
            String resId = jsonOne.get("resId").toString();
            String resValue = jsonOne.get("resValue").toString();
            String resValueName = jsonOne.get("resValueName").toString();
            String type = jsonOne.get("type").toString();
            String biaoshi = jsonOne.get("biaoshi").toString();

            if (biaoshi.equals("0")) {
                sys_auth_role_resource.setSubjectId(subjectId);
                sys_auth_role_resource.setRoleId(roleId);
                sys_auth_role_resource.setResId(resId);
                sys_auth_role_resource.setResValue(resValue);
                sys_auth_role_resource.setResValueName(resValueName);
                sys_auth_role_resource.setResType(type);
                sysauthroleresourceservice.save(sys_auth_role_resource);
            }
        }

        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write("1");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    @PostMapping("deleteRule")
    @ResponseBody
    private String deleteRule(String panelId) {
        try {
            log.info("deleteRole start, panelId = {}", panelId);
            //删除菜单中的权限
            int menuNumber = sys_menuService.deleteMenu(panelId);
            //删除角色的权限
            int roleMenuNumber = sysauthroleresourceservice.deleteByPanel(panelId);
            log.info("deleteRole end, menuNumber = {}, roleMenuNumber = {}", menuNumber, roleMenuNumber);
        } catch (Exception e) {
            log.error("deleteRule error -> {}", e);
            return "0";
        }
        return "1";
    }
}
